服务如何跑起来
服务如何跑起来
class URLSpec(object):
def __init__(self, pattern, handler_class, ···):
self.regex = re.compile(pattern)
self.handler_class = handler_class
class HTTPServer(object):
def __init__(self, request_callback, ···):
# request_callback为Application对象
self.request_callback = request_callback
self._sockets = {}
def listen(self, port, address=""):
self.bind(port, address)
self.start(1)
def bind(self, port, address=None, family=socket.AF_UNSPEC):
# getaddrinfo函数能够处理名字到地址以及服务到端口这两种转换,返回的是一个sockaddr结构的链表而不是一个地址清单
for res in socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, socket.AI_PASSIVE | socket.AI_ADDRCONFIG):
sock = socket.socket(af, socktype, proto)
sock.setblocking(0)
sock.bind(sockaddr)
sock.listen(128)
self._sockets[sock.fileno()] = sock
def start(self, num_processes=1):
if not self.io_loop:
self.io_loop = ioloop.IOLoop.instance()
for fd in self._sockets.keys():
self.io_loop.add_handler(fd, self._handle_events, ioloop.IOLoop.READ)
# IOLoop (fd handler callback timeout)
class IOLoop(object):
def __init__(self, impl=None):
self._impl = impl or _poll()
self._handlers = {}
def instance(cls): # current()
if not hasattr(cls, "_instance"):
cls._instance = cls()
return cls._instance
def add_handler(self, fd, handler, events):
self._handlers[fd] = stack_context.wrap(handler)
self._impl.register(fd, events | self.ERROR)
if hasattr(select, "epoll"):
# Python 2.6+ on Linux
_poll = select.epoll
elif hasattr(select, "kqueue"):
# Python 2.6+ on BSD or Mac
_poll = _KQueue
else:
try:
# Linux systems with our C module installed
import epoll
_poll = _EPoll
except:
# All other systems
import sys
if "linux" in sys.platform:
logging.warning("epoll module not found; using select()")
_poll = _Select